<?php

namespace app\controllers;


use app\components\BaseController;
use app\models\Book;
use app\models\Meta;
use app\widgets\SiteMapWidget;
use yii\db\Exception;
use yii\httpclient\Client;

class ApiController extends BaseController {

    public $enableCsrfValidation = FALSE;

    /**
     * @return array|bool
     * @throws Exception
     */
    public function actionBanner() {
        $banners = json_decode($this->getParam('banners'), TRUE);
        foreach ($banners as $banner) {
            $book = Book::findOne(['title' => $banner['name']]);
            if (!$book) {
                continue;
            }
            $data = ['name' => $banner['name'], 'description' => $banner['src'], 'sort' => $book['id']];
            Meta::saveMeta($data, Meta::TYPE_BANNER);
        }
        return $this->success();
    }

    public function actionExists() {
        $model = Book::findOne(['title' => $this->getParam('title')]);
        return $model ? $this->success($model) : $this->error();
    }

    public function actionPostSave() {
        $params = $this->getParam();
        $model = new Book();
        return $model->saveBook($params);
    }

    public function actionBuild() {
        return Book::find()->select('title, last_item')->indexBy('title')->asArray()->all();
    }

    public function actionFlush() {
        return \Yii::$app->cache->flush();
    }

    public function actionSiteMap() {
        return SiteMapWidget::widget();
    }

    public function actionBaiduPush($offset = 0) {
        $items = Book::find()->select('id')->orderBy('id desc')->asArray()->limit(20)->offset($offset)->all();
        $urls = [];
        foreach ($items as $item) {
//            $urls[] = Url::to(['comic/detail', 'id' => $item['id']]);
            $urls[] = "https://www.mh01.net/comic/{$item['id']}.html";

        }
        $client = new Client([
            'baseUrl' => 'http://data.zz.baidu.com',
            'transport' => 'yii\httpclient\CurlTransport'
        ]);

        $urls = implode("\n", $urls);
        $response = $client->post('urls?site=https://www.mh01.net&token=0TipAZCheESu8Ce3', $urls)->send();
        return $response->content;
    }
}